package cn.zlj.pethome.org.service.impl;

import cn.zlj.pethome.basic.QueryResult;
import cn.zlj.pethome.org.domain.TDepartment;
import cn.zlj.pethome.org.domain.TEmployee;
import cn.zlj.pethome.org.mapper.DepartmentMapper;
import cn.zlj.pethome.org.query.QueryPage;
import cn.zlj.pethome.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<TDepartment> getList() {
        List<TDepartment> list = departmentMapper.getList();
       Map<Long,TDepartment> parent = list.stream().collect(Collectors.toMap(TDepartment::getId,e -> e));

        List<TDepartment> result = new ArrayList<>();
        for (TDepartment dept : list) {
            if(dept.getParentId()==null){
             result.add(dept);
            }else{
                //用父级id获取到父级
                TDepartment dept1 = parent.get(dept.getParentId());
                //在把当前部门加入到父级的子部门
                dept1.getChildren().add(dept);
            }
        }
        return result;
    }

    @Override
    public QueryResult<TDepartment> queryPage(QueryPage page) {
        List<TDepartment> tDepartments = departmentMapper.queryPage(page);
        QueryResult<TDepartment> tDepartmentQueryResult = new QueryResult<>();
        tDepartmentQueryResult.setRows(tDepartments);
        Integer integer = this.queryPageCount(page);
        tDepartmentQueryResult.setTotals(integer);
        return tDepartmentQueryResult;
    }

    @Override
    public Integer queryPageCount(QueryPage page) {
        return departmentMapper.queryPageCount(page);
    }

    @Override
    @Transactional
    public void del(Long id) {
        departmentMapper.del(id);
    }

    @Override
    public TDepartment getOne(Long id) {
        return departmentMapper.getOne(id);
    }

    @Override
    @Transactional
    public void update(TDepartment tDepartment) {
       departmentMapper.update(tDepartment);
    }

    @Override
    @Transactional
    public void save(TDepartment tDepartment) {
        departmentMapper.save(tDepartment);
    }

    @Override
    public void batchDel(List<Long> ids) {
        departmentMapper.batchDel(ids);
    }
}
